package net.wangliping.android.tools.taskmanager;

import java.util.List;

import net.wangliping.android.tools.R;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class TaskAdapter extends BaseAdapter implements OnCheckedChangeListener {

	private LayoutInflater mInflater;
	private List<Programe> mPkgs;
	private final Context mContext;

	public TaskAdapter(Context context, List<Programe> pkgs) {
		mContext = context;
		mInflater = LayoutInflater.from(context);
		mPkgs = pkgs;
	}

	public int getCount() {
		return mPkgs.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder;

		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.taskmanager_list_item,
					null);

			holder = new ViewHolder();
			holder.taskName = (TextView) convertView.findViewById(R.id.task_app_name);
			holder.taskDetail = (TextView) convertView.findViewById(R.id.task_app_detail);
			holder.taskIcon = (ImageView) convertView.findViewById(R.id.task_app_icon);
			holder.taskCheck = (CheckBox) convertView.findViewById(R.id.task_app_check);
			
			holder.taskCheck.setOnCheckedChangeListener(this);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		Programe pkg = mPkgs.get(position);
		holder.taskName.setText(pkg.getName());
		holder.taskIcon.setImageDrawable(pkg.getIcon());
		holder.taskDetail.setText(pkg.isSystemApp() ? R.string.app_build_in : R.string.app_downloads);
		holder.taskCheck.setChecked(pkg.isChecked());
		holder.taskCheck.setTag(pkg); // What else can I do for record the package whether checked?

		return convertView;
	}

	static class ViewHolder {
		TextView taskName;
		TextView taskDetail;
		ImageView taskIcon;
		CheckBox taskCheck;
		TextView taskSize;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		Object obj = buttonView.getTag();
		if (obj != null) {
			Programe pkg = (Programe)obj;
			pkg.setChecked(isChecked);
		}
	}
}
